//
//  ImageDownLoadMgr.m
//  WoWeibo
//
//  Created by apple on 11-11-25.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ImageDownLoadMgr.h"
#import "ImageLoadingOperation.h"
#import "MD5Extension.h"
#import "PicCacheHelper.h"


@implementation ImageDownLoadMgr

- (id)init {
	self = [super init];
	if (self != nil) {
		cachedImages = [[NSMutableDictionary alloc] init];
		operationQueue = [[NSOperationQueue alloc] init];
		listLock = [[NSLock alloc] init];
        [operationQueue setMaxConcurrentOperationCount:10];
		capacityNum = 50;
		cachedKey = [[NSMutableArray alloc] init];
        
        _cacheHelper = [[PicCacheHelper alloc] init];
	}
	
	return self;
}

- (id)initWithCachedCapacity:(NSInteger)numItems {
	self = [super init];
	if (self != nil) {
		cachedImages = [[NSMutableDictionary alloc] initWithCapacity:numItems];
		operationQueue = [[NSOperationQueue alloc] init];
		listLock = [[NSLock alloc] init];
        [operationQueue setMaxConcurrentOperationCount:10];
		capacityNum = numItems;
		cachedKey = [[NSMutableArray alloc] init];
        
        _cacheHelper = [[PicCacheHelper alloc] init];
	}
	
	return self;
}

- (void)dealloc {
	[cachedImages release];
	[operationQueue release];
	[cachedKey release];
	[listLock release];
	[super dealloc];
}


#pragma mark -
#pragma mark Cached Image Loading

- (UIImage *)cachedImageForURL:(NSURL *)url target:(id)object {	

	[listLock lock];
	id cachedObject = [cachedImages objectForKey:url];
    if (cachedObject == nil)
	{
        UIImage *image = [_cacheHelper getImage:[url.absoluteString MD5]];
        if(image != nil) {
                        
            cachedObject = image;
        }else {
                     
            ImageLoadingOperation *operation = [[ImageLoadingOperation alloc] initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)];
            [cachedImages setObject:operation forKey:url];
            [operation addNotify:object];
            [operationQueue addOperation:operation];
            [operation release];
        }
    }
	else 
	{
		if ([cachedObject isKindOfClass:[ImageLoadingOperation class]]) 
		{            
			[(ImageLoadingOperation *)cachedObject addNotify:object];
			[listLock unlock];
			return nil;
		}
	}
	[listLock unlock];
	
	return cachedObject;
}

- (void)didFinishLoadingImageWithResult:(NSDictionary *)result
{
    NSURL *url = [result objectForKey:@"url"];
	if (url == nil) 
	{
		return;
	}

    UIImage *image = [result objectForKey:@"image"];

	[listLock lock];
    
	// 判断当前列表是否已满
	if ([cachedKey count] >= capacityNum)
	{
        NSArray *keyArray = [cachedImages allKeys];
        for (NSURL *key in keyArray) {
            
            NSObject *object = [cachedImages objectForKey:key];
            if([object isKindOfClass:[UIImage class]])
                [_cacheHelper storeImage:(UIImage *)object withMD5:[key.absoluteString MD5]];
        }
        
        [cachedImages removeAllObjects];
        [cachedKey removeAllObjects];
//		NSLog(@"当前缓存数量：%d", [cachedImages count]);
//		int deleteNum = 0;
//		while (deleteNum < 10) 
//		{
//			[cachedImages removeObjectForKey:[cachedKey objectAtIndex:0]];
//			[cachedKey removeObjectAtIndex:0];
//			deleteNum++;
//		}
	}
	
	if (image == nil) 
	{
		[cachedImages removeObjectForKey:url];
	}
	else 
	{
		[cachedImages setObject:image forKey:url];
		[cachedKey addObject:url];
	}
	[listLock unlock];
}

- (BOOL)removeAllCachedImage {
	[listLock lock];
	[cachedImages removeAllObjects];
	[cachedKey removeAllObjects];
	[listLock unlock];
	return YES;
}

@end

